package cn.com.homeyoda.aimate.aihealth.ui.health.frragment;

import android.content.Context;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.datepicker.MaterialDatePicker;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.bean.MyselfPlanBean;
import cn.com.homeyoda.aimate.aihealth.bean.WeekBean;
import cn.com.homeyoda.aimate.aihealth.manager.UserInfoManager;
import cn.com.homeyoda.aimate.aihealth.ui.health.SportPlanActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.VideoPlayActivity;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.WeekCourseAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.health.adapter.WeekSelectAdapter;
import cn.com.homeyoda.aimate.aihealth.views.CenterDialog;
import cn.com.homeyoda.aimate.aihealth.views.SpaceItemDecoration;

public class MyPlanFragment extends Fragment {

    private SportPlanActivity sportPlanActivity;

    private WeekSelectAdapter weekSelectAdapter;
    private WeekCourseAdapter weekCourseAdapter;

    private View mRootView;

    private TextView tv_train_name, tv_title1, tv_desc, tv_tips, joinPlan;
    private View region_1, region_2, emptyView;

    private MyselfPlanBean.DataBean planBean;

    private RecyclerView rv_week, rv_course;

    private List<WeekBean> weekList = new ArrayList<>();

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        sportPlanActivity = (SportPlanActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_my_sport, container, false);

            tv_train_name = mRootView.findViewById(R.id.tv_train_name);
            tv_title1 = mRootView.findViewById(R.id.tv_title1);
            tv_desc = mRootView.findViewById(R.id.tv_desc);
            tv_tips = mRootView.findViewById(R.id.tv_tips);
            joinPlan = mRootView.findViewById(R.id.joinPlan);

            rv_week = mRootView.findViewById(R.id.rv_week);
            rv_course = mRootView.findViewById(R.id.rv_course);

            region_1 = mRootView.findViewById(R.id.region_1);
            region_2 = mRootView.findViewById(R.id.region_2);
            emptyView = mRootView.findViewById(R.id.emptyView);
            // 更多计划
            mRootView.findViewById(R.id.btn_my_plan).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sportPlanActivity.changeMoreFragment();
                }
            });

            joinPlan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 退出
                    sportPlanActivity.caclePlan("", planBean.getPlanId());
                }
            });

            mRootView.findViewById(R.id.btn_date_select).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 更多日期
                    selectDay();
                }
            });

        }

        upDateUi();

        return mRootView;
    }

    private void selectDay() {
        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                // .setTheme(R.style.ThemeOverlay_App_DatePicker)
                .build();

// 显示日期选择器
        datePicker.show(sportPlanActivity.getSupportFragmentManager(), "DATE_PICKER");

// 处理选择结果
        datePicker.addOnPositiveButtonClickListener(selection -> {
            // 选择的日期时间戳（UTC毫秒）
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            calendar.setTimeInMillis(selection);
            sportPlanActivity.getViewModel().selectNewWeek(calendar);

            SimpleDateFormat format = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String selectedDate = format.format(calendar.getTime());
                sportPlanActivity.getViewModel().initPlanDetails(sportPlanActivity.getViewModel().planUserStateLiveData.getValue().getFaceId(),
                        UserInfoManager.getInstance().selfSportPlan.getPlanId(), selectedDate);
            }
        });
    }


    public void upDateUi() {
        planBean = UserInfoManager.getInstance().selfSportPlan;
        if (planBean != null) {

            region_1.setVisibility(View.VISIBLE);
            region_2.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);

            tv_train_name.setText(planBean.getPlanName());
            tv_title1.setText(planBean.getTitle());
            tv_desc.setText(planBean.getIntro());
            tv_tips.setText(planBean.getJoinDayNum());
            sportPlanActivity.initWeek();
            initWeekView();
        } else {
            region_1.setVisibility(View.INVISIBLE);
            region_2.setVisibility(View.INVISIBLE);
            emptyView.setVisibility(View.VISIBLE);

        }
    }

    private void initWeekView() {

        if (weekSelectAdapter == null) {
            weekSelectAdapter = new WeekSelectAdapter(R.layout.item_week_select, weekList, sportPlanActivity);
            rv_week.setLayoutManager(new LinearLayoutManager(sportPlanActivity, LinearLayoutManager.HORIZONTAL, false));
            rv_week.addItemDecoration(new SpaceItemDecoration(0, 0, 10, 0));
            rv_week.setAdapter(weekSelectAdapter);

            weekSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    sportPlanActivity.setWeek(position);
                }
            });
        } else {
            weekSelectAdapter.setNewData(weekList);
        }


        if (weekCourseAdapter == null) {
            weekCourseAdapter = new WeekCourseAdapter(R.layout.item_week_couse_select, planBean.getSubjectList(), sportPlanActivity);
            rv_course.setLayoutManager(new LinearLayoutManager(sportPlanActivity, LinearLayoutManager.HORIZONTAL, false));
            rv_course.addItemDecoration(new SpaceItemDecoration(0, 0, 10, 0));
            rv_course.setAdapter(weekCourseAdapter);

            weekCourseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Bundle bundle = new Bundle();
                    bundle.putString("videoUrl", weekCourseAdapter.getData().get(position).getVideoUrl());
                    sportPlanActivity.startActivity(VideoPlayActivity.class, bundle);
                }
            });
        } else {
            weekCourseAdapter.setNewData(planBean.getSubjectList());
        }

    }

    public void setWeek(int week) {
        if (weekSelectAdapter != null) {
            weekSelectAdapter.setSelectPosition(week);
        }
    }

    public void upDateVideoList(List<MyselfPlanBean.DataBean.SubjectListBean> subjectListBeans) {
        weekCourseAdapter.setNewData(subjectListBeans);
    }


    public void updateWeek(List<WeekBean> weekList) {
        this.weekList = weekList;
        if (weekSelectAdapter != null) {
            weekSelectAdapter.setNewData(weekList);
        }
    }


}
